package com.cainli.gcmdemo;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.http.impl.conn.Wire;

public class Utils {
	private static FileWriter writer;
	public static boolean createDataFile(String path) {
		try {
			File f = new File(path);
			if (f != null && f.exists()) {
				if (f.delete()) {
					return f.createNewFile();
				}
				return false;
			} else {
				return f.createNewFile();
			}
		} catch (Exception e) {
			return false;
		}
	}

	public static boolean exists(String filepath){
		File f = new File(filepath);
		return f.exists();
	}
	
	
	public static void saveID(String regId) {
		if(!exists(Constants.ID_FILE_PATH)){
			writeDataToFile(Constants.ID_FILE_PATH,regId);
		}
	}
	
	public static void saveMsg(String string) {
		writeDataToFile(Constants.DATA_FILE_PATH,string);
	}

	public static void writeDataToFile(String path, final String msg) {
		try {
			File f = new File(path);
			if (!f.exists()) {
				try {
					f.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
					return;
				}
			}
			FileWriter writer = new FileWriter(f, true);
			writer.write(msg);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	public static void saveMsg2(String msg) throws IOException {
		if(writer != null){
			save(msg);
		}
	}

	static int count = 0;
	public static void save(String msg) throws IOException {
		if(writer!=null){
			count++;
			writer.write(msg);
			if(count == 100){
				writer.flush();
				count =0;
			}
		}
	}
	
	public static void close() throws IOException {
		if(writer != null){
			writer.flush();
			writer.close();
			writer = null;
		}
	}

	public static boolean openFile() throws IOException {
		if(writer == null){
			File f = new File(Constants.DATA_FILE_PATH);
			if (!f.exists()) {
				try {
					f.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
			}
			writer = new FileWriter(f, true);
			return true;
		}
		return true;
	}
}
